<?php
class model_user extends model_weixin{
	
    
    /**
     * @info 获取通过微信渠道过来的用户的一系列信息
     * @author jackie yang
     * @date 20140703
     * @param $openid  微信的openid
     * @return array  用户信息
     */
    public static function get_userinfo($openid=''){
        $return = array();
        if(empty($openid)){
            return $return;
        }
        $base = self::get_user_by_openid($openid,WEIXINHAO);
        if($base == FALSE){
            $base = array();
        }
        return $base;
    }
    
    
    
    /**
     * @info 注册账号操作
     * @author jackie yang
     * @date 20140705
     * @param openid  关注者的微信openid or 网页授权拿到的微信openid
     */
    public static function resgiter($openid=''){
        if(!empty($openid)){
            $base = model_user::get_subscribe_user($openid);
            unset($base['remark']);//去除无用的字段
            unset($base['errcode']);
            if($base != FALSE){
                $base['weixin_id'] = WEIXINHAO;
                //判断此用户是否存在
                $row = self::get_user_by_openid($openid,WEIXINHAO);
                if($base['subscribe']==1){ //关注者
                    $base['subscribe_time'] = date("Y-m-d H:i:s",$base['subscribe_time']);
                    $center['openid'] = $base['openid'];
                    if(!empty($row)){
                        //更新下
                        $res = self::update_weixin_user_info($base,$openid,WEIXINHAO);
                        if($res <= 0){
                            framework_static_function::write_log('user base update subscribe failed:openid:'.$openid,'weixin_user');
                        }
                    }else{
                        self::add_weixin_user($base);
                    }
                }elseif($base['subscribe']==0){  //未关注  
                    if(!empty($row)){
                        //更新下
                        $res = self::update_weixin_user_info($base,$openid,WEIXINHAO);
                        if($res <= 0){
                            framework_static_function::write_log('user base update unsubscribe failed:openid:'.$openid,'weixin_user');
                        }
                    }else{
                        self::add_weixin_user($base);
                    }
                }//end 是否关注
            }
        }
    }
    /**
     * @info 根据openid 查询用户base表信息
     * @author jackie yang
     * @date 20140703
     * @return $data  array | false
     */
    public static function get_user_by_openid($openid='',$weixin_id=''){
        if(empty($openid) || empty($weixin_id)){
            return FALSE;
        }
        $sql = 'SELECT 
                    `openid`,`subscribe`,`nickname`,`headimgurl`,`weixin_id`, `user_id`,`user_type`
                FROM 
                    `weixin_user` 
                WHERE 
                    `openid`=:openid and `weixin_id`=:weixin_id and delete_flag=0';
        try {
        	$st = self::DB()->dbh->prepare($sql);
        	$binds = array(':openid'=>$openid,':weixin_id'=>$weixin_id);
        	$st->execute($binds);
        	$data = $st->fetch();
        	return $data;
        } catch (Exception $e) {
        	framework_static_function::write_log(__METHOD__.":".$e->getMessage(),'weixin_sql');
        	return array();
        }
        /* 
        $data = self::DB()->queryRow($sql ,array(':openid'=>$openid,':weixin_id'=>$weixin_id));
        return $data; */
    }
	/**
     * @info 微信用户表weixin_user
     * @author jackie yang
     * @datetime 20140705
     * @param  $data  array
     */
    public static function add_weixin_user($data){
        try{
            $sql = "INSERT INTO weixin_user SET ";
            $binds = array();
            foreach ($data as $k => $v) {
                $sql .= '`' . $k . '`=:' . $k . ',';
                $binds[':' . $k] = $v;
            }
            $sql .= 'raw_add_time=NOW(),raw_update_time=now()';
            $arr=self::DB() -> dbh -> prepare($sql);
            $rel = $arr->execute($binds);
            if($rel == TRUE) {
               return self::DB()->dbh->lastInsertId();
            }
        }catch(Exception $e){
            framework_static_function::write_log(__METHOD__.":".$e->getMessage(),'weixin_sql');
            return 0;
        }
        return 0;
    }
    
    /**
     * @info 修改用户信息
     * @author jackie yang
     */
    public static function update_weixin_user_info($data,$openid,$weixin_id){
        if(empty($data) || empty($openid) || empty($weixin_id)){
            return FALSE;
        }
        unset($data['openid']);
        unset($data['weixin_id']);
        unset($data['errmsg']);
        try{
            $sql = 'UPDATE `weixin_user` SET ';
            $binds = array();
            foreach ($data as $k => $v) {
                $sql .= '`' . $k . '`=:' . $k . ',';
                $binds[':' . $k] = $v;
            }
            $binds[':openid'] = $openid;
            $binds[':weixin_id'] = $weixin_id;
            $sql = trim($sql,',');
            $sql .= ' WHERE `openid`=:openid and `weixin_id`=:weixin_id'; 
            $stm=self::DB() -> dbh -> prepare($sql);
            $rel = $stm->execute($binds);
            $rowCount = $stm -> rowCount();
            return $rowCount;
        }catch(Exception $e){
            framework_static_function::write_log(__METHOD__.":".$e->getMessage(),'weixin_sql');
            return 0;
        }
        return 0;
    }
    
    /**
     * @info 获取关注者用户信息
     * @author jackie yang
     */
    public static function get_subscribe_user($openid=''){
        if(!empty($openid)){
            $url = 'https://api.weixin.qq.com/cgi-bin/user/info?';
            $url .= 'access_token='.self::get_access_token();
            $url .= '&openid='.$openid;
            $url .= '&lang=zh_CN';
            framework_static_function::write_log($url,'weixin');
            $info = model_weixin::http_post($url,'');
            framework_static_function::write_log($info,'weixin');
            $info = json_decode($info,TRUE);
            if(empty($info) || array_key_exists('errcode', $info)){
            	if($info['errcode'] == 42001) { //access_token过期
            		$access_token = self::get_access_token_by_weixin();//重新获取access_token
            		framework_static_function::write_log($access_token,'access_token');
            		self::get_subscribe_user($openid);
            	} else {
            		framework_static_function::write_log(__METHOD__.':获取关注者用户信息错误:'.json_encode($info),'weixin');
            		return FALSE;
            	}                
            }
            return $info; 
        }
        return FALSE;
    }
	/**
     * @info 外部用户注册
     * @author jackie yang
     * @datetime 20141101
     * @param  $data  array
     * @param $table string weixin_register_user|weixin_sales_user
     */
    public static function add_register_user($data,$table='weixin_register_user'){
        try{
            $sql = "INSERT INTO ".$table." SET ";
            $binds = array();
            foreach ($data as $k => $v) {
                $sql .= '`' . $k . '`=:' . $k . ',';
                $binds[':' . $k] = $v;
            }
            $sql .= 'raw_add_time=NOW(),raw_update_time=now()';
            $arr=self::DB() -> dbh -> prepare($sql);
            $rel = $arr->execute($binds);
            if($rel == TRUE) {
               return self::DB()->dbh->lastInsertId();
            }
        }catch(Exception $e){
            framework_static_function::write_log(__METHOD__.":".$e->getMessage(),'weixin_sql');
            return 0;
        }
        return 0;
    }
    /**
     * 
     * 判断用户名是否可注册
     * @param string $User_Account
     * @return bool
     */
    public static function is_exists_account($User_Account) {
    	$sql = "select count(*) from weixin_register_user where User_Account=:User_Account and delete_flag=0";
    	try {
    		$binds = array(
    			':User_Account' => $User_Account
    		);
    		$st = self::DB()->dbh->prepare($sql);
    		$st->execute($binds);
    		return $st->fetchColumn();
    	}catch(Exception $e){
            framework_static_function::write_log(__METHOD__.":".$e->getMessage(),'weixin_sql');
            return 0;
        }
    }
    /**
     * 
     * 判断微信账号是否注册过
     * @param string $openid
     * @param string $table weixin_register_user|weixin_sales_user
     * @return array $data
     */
    public static function is_openid_registered($openid,$table='weixin_register_user') {
    	if($table == 'weixin_register_user') {
    		$sql = 'select openid,User_Account,Deal_State from '.$table.' where openid=:openid';
    	} else {
    		$sql = 'select openid,sales_name,deal_state from '.$table.' where openid=:openid';
    	}    	
    	try {
    		$binds = array(
    			':openid' => $openid
    		);
    		$st = self::DB()->dbh->prepare($sql);
    		$st->execute($binds);
    		$data = $st->fetch();
    		return $data;
    	}catch(Exception $e){
            framework_static_function::write_log(__METHOD__.":".$e->getMessage(),'weixin_sql');
            return array();
        }
    }
	/**
     * @info 修改外部用户注册信息，审核失败或者已删除用户可以通过此方法重新发起注册申请
     * @author jackie yang
     */
    public static function update_weixin_register_user_info($data,$openid,$table='weixin_register_user'){
        if(!is_array($data) || empty($data) || empty($openid)){
            return 0;
        }
        unset($data['openid']);
        $data['delete_flag'] = 0;
        try{
            $sql = 'UPDATE `'.$table.'` SET ';
            $binds = array();
            foreach ($data as $k => $v) {
                $sql .= '`' . $k . '`=:' . $k . ',';
                $binds[':' . $k] = $v;
            }
            $binds[':openid'] = $openid;
            $sql = trim($sql,',');
            $sql .= ' WHERE `openid`=:openid'; 
            $stm=self::DB() -> dbh -> prepare($sql);
            $rel = $stm->execute($binds);
            $rowCount = $stm -> rowCount();
            return $rowCount;
        }catch(Exception $e){
            framework_static_function::write_log(__METHOD__.":".$e->getMessage(),'weixin_sql');
            return 0;
        }
        return 0;
    }
    
    /**
     * 
     * 获取用户分类
     * @param int $parent_id (1:内部用户，2：外部用户)
     */
    public static function get_user_category_list($parent_id) {
    	$sql = 'select user_category_id,category_name from weixin_user_category where parent_id=:parent_id and delete_flag=0';
    	try {
    		$binds = array(
    			':parent_id' => $parent_id
    		);
    		$st = self::DB()->dbh->prepare($sql);
    		$st->execute($binds);
    		$data = $st->fetchAll();
    		return $data;
    	}catch(Exception $e){
            framework_static_function::write_log(__METHOD__.":".$e->getMessage(),'weixin_sql');
            return array();
        }
    }
    /**
     * 
     * 获取注册用户的信息
     * @param string $openid 微信openid
     * @param string $table weixin_register_user|weixin_sales_user
     */
    public static function get_register_userinfo_by_openid($openid,$table) {
    	$sql = "select * from ".$table." where openid=:openid and delete_flag=0";
    	try {
    		$binds = array(
    			':openid' => $openid
    		);
    		$st = self::DB()->dbh->prepare($sql);
    		$st->execute($binds);
    		$data = $st->fetch();

            //framework_static_function::write_log(__METHOD__."-sql:".$sql.'--'.$openid.'---'.$table.'---'.json_encode($data),"sql");


    		return $data;
    	}catch(Exception $e){
            framework_static_function::write_log(__METHOD__.":".$e->getMessage(),'weixin_sql');
            return array();
        }
    }
}